#pragma once
#include <QElapsedTimer>
#include <QThread>
#include <QVector>
#include <QMutex>
#include <QWaitCondition>
#include "../core/SortRenderer.cuh"
#include "../thread/Randomizer.h"

struct SortConfig {
    int N = 128;
    Algo algo = Algo::Bubble;
    ShuffleMode shuffle = ShuffleMode::Random;
    double speedMult = 1.0; // 0.2–10×
};

class SortThread : public QThread {
    Q_OBJECT

public:
    explicit SortThread(QObject *parent = nullptr);

    void applyConfig(SortConfig cfg); // 改配置并暂停
    void updateSpeed(double s); // 运行中改倍率
    void togglePause();

    void forceShuffle();

    void forcePause();

    void stop();

    bool isPaused(); // 线程安全查询
    double currentSpeed();

signals:
    /* 额外携带 tag 数组 */
    void frameReady(const QVector<uint32_t> &data,
                    const QVector<int> &tag,
                    SortStats stat);

protected:
    void run() override;
    friend void parMerge(QVector<uint32_t>& a,
                        SortStats& st, SortThread* self,
                        QElapsedTimer& tim);
    friend void parQuick(QVector<uint32_t>& a,
                     SortStats& st, SortThread* self,
                     QElapsedTimer& tim);
    friend void parTim(QVector<uint32_t> &a,
                       SortStats &st, SortThread *self, QElapsedTimer &tim);

    friend void pushFrame(const QVector<uint32_t>& src,
                             SortStats&              st,
                             SortThread*             self,
                             QElapsedTimer&          tim,
                             double                  delayFactor = 1.0);

private:
    QVector<uint32_t> m_host;
    QVector<int> m_tag; // 每条颜色 ID（-1 = 默认 HSV）
    SortConfig m_cfg;
    QMutex m_mutex;
    QWaitCondition m_wait;
    bool m_pause = true;
    bool m_abort = false;
    bool m_shuffleReq = false;
};
